<?php
class Mysql
{
	private static $instance = null;
	
	
	private $connection = null;
	
	public static function instance( $server = null )
	{
		if( $server == null )
		{
			if( class_exists('Controller'))
				$server = Controller::$configs['db'];
		}
		
		if( !self::$instance )
		{
			self::$instance = new self();
			self::$instance->connect( $server );
		}
		return self::$instance;
	}
	
	private function connect( $server )
	{
	
		
		$this->connection = mysql_connect( $server['host'], $server['dbuser'], $server['dbpass'] ) or die("Could not connect to database server: ".$server['host']." with user: ".$server['dbuser']);
		mysql_select_db( $server['dbname'], $this->connection ) or die(mysql_error());
	}
	
	public function query( $queryString )
	{
		return mysql_query( $queryString, $this->connection ) or die(mysql_error( $this->connection ));
	}
	
	public function queryArray( $queryString )
	{
		$result = mysql_query( $queryString, $this->connection ) or die(mysql_error());
		$rows = array();
		while( $row = mysql_fetch_assoc( $result ) )
		{
			$rows[] = $row;
		}
		return $rows;
	}
	
	public function getRandomRecord( $table )
	{
		$query = "SELECT * FROM `{$table}` ORDER BY RAND() LIMIT 0,1";
		$result = mysql_query( $query, $this->connection );
		if( $row = mysql_fetch_assoc($result))
		{
			return $row;
		}
		return false;
	}
	
	public function disconnect()
	{
		mysql_close( $this->connection );
	}
	
}
?>